package controller;

import DataAcess.Bus;
import DataAcess.linkedBus;
import Interface.MainGui;
import java.awt.Color;
import java.util.ArrayList;
import java.util.TreeSet;
import javax.swing.JOptionPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;


/*
 * Class ID	: SE715
 * Student ID	: 02967
 * Student Name : Vu Ngoc Trung
 * Due Date     : Jul 21, 2013
 * I declare that this assignment is my own work in accordance with FPT Policy.
 */
public class SearchStartEndController implements controller.Controller {

    private MainGui form;
    ArrayList<Bus> arrbus;
    controller.Controller controller;
    int mouseSelectedIndex;

    public SearchStartEndController(ArrayList arrbus, controller.Controller controller, MainGui mg) {
        this.arrbus = arrbus;
        form = mg;
        this.controller = controller;
    }

    @Override
    public void handleEvent(String event) {

        if (event.equals("View")) {
            Viewbus();
        }
        if (event.contains("ListAll")) {
            ShowBang();
        }
        if (event.equals("SearchStartEnd")) {
            SearchStartEnd();
        }
    }

    public void view(Bus bus) {
        //show full information about bus this interface
        form.lbNameRoute.setText(bus.getName());
        form.lbNoRoute.setText(Integer.toString(bus.getNumber()));
        form.taGoRoute.setText(bus.getGo());
        form.taBackRoute.setText(bus.getBack());
        form.taGoRoute.setEditable(false);
        form.taBackRoute.setEditable(false);
    }

    private void ShowBang() {
        // list all bus
        int i = 0;
        for (Bus bus : arrbus) {
            form.tbRoute.setValueAt(bus.getNumber(), i, 0);
            form.tbRoute.setValueAt(bus.getName(), i, 1);
            i++;
        }
    }

    public void Viewbus() {
        //check null row in table
        if (form.tbRoute.getValueAt(form.tbRoute.getSelectedRow(), 0) != null) {
            //get location of row are already chosen
            mouseSelectedIndex = form.tbRoute.getSelectedRow();
            Highlighter.HighlightPainter painter =
                    new DefaultHighlighter.DefaultHighlightPainter(Color.GREEN);

            //check null row in table
            if (!(form.tbRoute.getValueAt(mouseSelectedIndex, 0).equals(""))) {
                Bus bus = null;
                //find and show bus to table
                for (Bus bus1 : arrbus) {
                    if (bus1.getNumber() == form.tbRoute.getValueAt(mouseSelectedIndex, 0)) {
                        bus = bus1;
                    }
                }

                view(bus);
                //find location of street name in table to highlight
                int t1 = bus.getGo().trim().toLowerCase().indexOf(form.tfSearchStartRoute.getText().trim().toLowerCase());
                int t2 = bus.getBack().trim().toLowerCase().indexOf(form.tfSearchStartRoute.getText().trim().toLowerCase());
                int t3 = bus.getGo().trim().toLowerCase().indexOf(form.tfSearchEndRoute.getText().trim().toLowerCase());
                int t4 = bus.getBack().trim().toLowerCase().indexOf(form.tfSearchEndRoute.getText().trim().toLowerCase());

                //highlight street name
                form.taGoRoute.requestFocus(true);
                form.taBackRoute.requestFocus(true);
                if (t1 >= 0 && t3 >= 0) {
                    try {
                        form.taGoRoute.getHighlighter().addHighlight(t1, t1 + form.tfSearchStartRoute.getText().trim().length(), painter);
                        form.taGoRoute.getHighlighter().addHighlight(t3, t3 + form.tfSearchEndRoute.getText().trim().length(), painter);
                    } catch (BadLocationException ble) {
                    }
                }
                if (t2 >= 0 && t4 >= 0) {
                    try {
                        form.taBackRoute.getHighlighter().addHighlight(t2, t2 + form.tfSearchStartRoute.getText().trim().length(), painter);
                        form.taBackRoute.getHighlighter().addHighlight(t4, t4 + form.tfSearchEndRoute.getText().trim().length(), painter);
                    } catch (BadLocationException ble) {
                    }
                }
            }
        }
    }

    public void SearchStartEnd() {
        //clear table
        for (int j = 0; j < 80; j++) {
            for (int k = 0; k < 2; k++) {
                form.tbRoute.setValueAt("", j, k);
            }
        }
        int i = 0;
        // normalized street name
        String searchStart = form.tfSearchStartRoute.getText().toLowerCase();
        String searchEnd = form.tfSearchEndRoute.getText().toLowerCase();
        // normalized and find street name
        for (Bus bus : arrbus) {
            String busGo = bus.getGo().toLowerCase();
            String busBack = bus.getBack().toLowerCase();
            if ((busGo.contains(searchStart) && busGo.contains(searchEnd))
                    || (busBack.contains(searchStart)) && busBack.contains(searchEnd)) {
                form.tbRoute.setValueAt(bus.getNumber(), i, 0);
                form.tbRoute.setValueAt(bus.getName(), i, 1);
                i++;
            }
        }
        //show message if bus not found
        if (i == 0) {
            form.taBackRoute.setText("");
            form.taGoRoute.setText("");
            int a = JOptionPane.showConfirmDialog(form, "Không tìm thấy xe buýt\n"
                    + "Bạn có muốn tìm kiếm liên tuyến không?",
                    "Bus not found!", 0, 0, new javax.swing.ImageIcon(getClass().getResource("/Icon/findfail.png")));
            if (a == JOptionPane.YES_OPTION) {
                //show result of connecting bus was found
                form.tabChinh.setSelectedIndex(7);
                Lientuyen(searchStart, searchEnd);
            }
        }
    }

    public void Lientuyen(String start, String Cuoi) {
        ArrayList<Bus> len = new ArrayList();
        ArrayList<Bus> xuong = new ArrayList();
        String[] dau;
        String[] cuoi;
        TreeSet treeSet = new TreeSet();
        int lap = 0, in_tiep = 1;
        for (int i = 0; i < arrbus.size(); i++) {
            if (arrbus.get(i).getGo().toLowerCase().contains(start)) {
                len.add(arrbus.get(i));//xe di qua diem dau - A
            }
            if (arrbus.get(i).getGo().toLowerCase().contains(Cuoi)) {
                xuong.add(arrbus.get(i));//xe di qua diem cuoi - B
            }
        }

        for (int i = 0; i < len.size(); i++) {
            dau = len.get(i).getGo().toLowerCase().trim().split("-");//tach tuyen pho xe A di qua
            for (int j = 0; j < dau.length; j++) {//duyet qua cac tuyen pho xe A di qua
                for (int h = 0; h < xuong.size(); h++) {//duyet qua cac xe B 
                    cuoi = xuong.get(h).getGo().toLowerCase().trim().split("-");//tach tuyen pho xe B di qua
                    for (int k = 0; k < cuoi.length; k++) {
                        if (dau[j].equalsIgnoreCase(cuoi[k])) {
                            //add to treeset to avoid dubplicate
                            linkedBus bus = new linkedBus(len.get(i).getNumber(), cuoi[k].toUpperCase(), xuong.get(h).getNumber());
                            treeSet.add(bus);
                        }
                    }
                }
            }
        }
        boolean b = true;
        String s = "";
        ArrayList<linkedBus> listLinkedBus = new ArrayList();
        listLinkedBus.addAll(treeSet);
        
        // gathering all connect bus have same number start and showing to textarea
        for (int i = 0; i < listLinkedBus.size() - 1; i++) {
            if (b && i != listLinkedBus.size() - 2) {
                b = false;
                s = s + "\nLên xe " + listLinkedBus.get(i).getXe1() + "\n";
            } else {
                s = s + "Xuống tại: " + listLinkedBus.get(i).getDiemxuong() + "  Bắt tiếp xe "
                        + listLinkedBus.get(i).getXe2() + "\n";
            }
            if(i==listLinkedBus.size()){
                break;
            }
            if (listLinkedBus.get(i).getXe1() != listLinkedBus.get(i + 1).getXe1()) {
                b = true;
            }
        }
        if (s.equals("")) {
            //show message if can't found connecting bus
            form.taLienTuyen.setText("");
            JOptionPane.showMessageDialog(form, "Không tìm thấy liên kết!");
        } else {
            //showing to textarea
            form.taLienTuyen.setText(s);
        }
    }
}
